package com.chen.servicemap.remote;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.chen.internalcommon.constant.MapConfigConstants;
import com.chen.internalcommon.response.DirectionResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * @author chenLiuPing
 **/
@Service
@Slf4j
public class MapDirectionClient {

    @Value("${map.key}")
    private String mapKey;

    @Autowired
    private RestTemplate restTemplate;

    public DirectionResponse direction(String depLongitude, String depLatitude, String destLongitude, String destLatitude) {
        // 组装调用第三方地图接口url
        StringBuilder url = new StringBuilder();
        url.append(MapConfigConstants.DIRECTION_URL);
        // 组装出发地经纬度
        url.append("?origin=").append(depLongitude).append(",").append(depLatitude);
        // 组装目的地经纬度
        url.append("&destination=").append(destLongitude).append(",").append(destLatitude);
        // 组装返回结果类型参数
        url.append("&output=json");
        // 组装key
        url.append("&key=").append(mapKey);
        log.info("url:{}", url);

        // 接口调用
        String directionBody = restTemplate.getForEntity(url.toString(), String.class).getBody();
        return parseDirectionBody(directionBody);

    }

    private DirectionResponse parseDirectionBody(String directionBody) {
        // 从 directionBody中解析 distance 和 duration
        DirectionResponse directionResponse = null;
        JSONObject jsonObject = JSONObject.parseObject(directionBody);
        int status = jsonObject.getIntValue(MapConfigConstants.STATUS);
        if (status == 1) {
            JSONObject route = jsonObject.getJSONObject(MapConfigConstants.ROUTE);
            JSONArray paths = route.getJSONArray(MapConfigConstants.PATHS);
            JSONObject path = paths.getJSONObject(0);
            int distance = path.getIntValue(MapConfigConstants.DISTANCE);
            int duration = path.getIntValue(MapConfigConstants.DURATION);
            log.info("distance:{}", distance);
            log.info("duration:{}", duration);
            directionResponse = new DirectionResponse(distance, duration);
            return directionResponse;
        } else {
            log.info("请求高德web服务路径规划接口出错：{}", jsonObject);
            return directionResponse;
        }

    }

}
